package org.dimock.proxy;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public final class DefaultProxy implements java.lang.reflect.InvocationHandler {
	private ProxyContext context;
	
	DefaultProxy(ProxyContext context) {
		super();
		this.context = context;
	}
	
	private static Object newInstance(ProxyContext context, Class<?> target) {
		ClassLoader cl = target.getClass().getClassLoader();
		DefaultProxy proxy = new DefaultProxy(context);
		return Proxy.newProxyInstance(cl, new Class<?>[]{target},  proxy);
	}

    public Object invoke(Object proxy, Method m, Object[] args)	throws Throwable   {
    	Method redirectMethod = context.getMethodResolver().findMatchingMethod(context,m);
    	if ( (redirectMethod == null) && context.isRecursive() ) {
    		if ( m.getReturnType().isInterface() )
    			return newInstance(context, m.getReturnType()); 
    		if (m.getReturnType() == void.class)
    			return null;
    	}
    	return redirectMethod.invoke(context.getRedirect(), args);
	}


	


}
